/*
 * @Author: your name
 * @Date: 2019-09-25 09:48:29
 * @LastEditTime: 2019-11-08 17:33:10
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \IntelligentElderlyCare\client\app\src\projects\app\appStorage.ts
 */

import { getObject, log, Ref, Role } from "pao-aop";
import { CookieUtil } from "pao-aop-client";
import { COOKIE_KEY_CURRENT_USER, COOKIE_KEY_USER_ROLE, LOCAL_FUNCTION_LIST } from "src/business/mainForm/backstageManageMainForm";
import { IUserService, User } from "src/business/models/user";
import { AppServiceUtility } from "./appService";

/**
 * 工业互联网应用存储
 */
export class IntelligentElderlyCareAppStorage {

    /** 用户服务 */
    static userService_Fac?: Ref<IUserService>;
    /** 用户服务 */
    static get userService() {
        return getObject(IntelligentElderlyCareAppStorage.userService_Fac);
    }
    /** 处理全局数据事件 */
    static async handleGlobalDataEvent() {
        try {
            const currentUser = await AppServiceUtility.person_org_manage_service.get_current_user_info!()!;
            const user = { id: '', role_id: '', name: '', address: '', 'personnel_info': undefined };

            const func_list = await AppServiceUtility.login_service.get_function_list!()!;

            localStorage.setItem(LOCAL_FUNCTION_LIST, JSON.stringify(func_list));
            if (currentUser && currentUser.length > 0) {
                const address = (currentUser[0] as any).personnel_info.address;
                user.id = currentUser[0].id;
                user.name = currentUser[0].name;
                user.address = address;
                user.role_id = currentUser[0].role_id;
                if (currentUser[0].personnel_info) {
                    user['personnel_info'] = currentUser[0].personnel_info;
                }
            }
            CookieUtil.save(COOKIE_KEY_CURRENT_USER, user!);
            // const roles = await IntelligentElderlyCareAppStorage
            //     .userService!
            //     .get_current_role!()!;
            // CookieUtil.save(COOKIE_KEY_USER_ROLE, roles!);
            // console.log('roles', roles!);
        } catch (error) {
            log('IntelligentElderlyCareAppStorage', `${error.message}`);
        }
    }
    /** 获取当前用户角色 */
    static getCurrentUserRoles() {
        return CookieUtil.read<Role[]>(COOKIE_KEY_USER_ROLE);
    }

    /** 获取用户信息 */
    static getCurrentUser() {
        return CookieUtil.read<User>(COOKIE_KEY_CURRENT_USER);
    }

    /** 退出登录，清除cookies */
    static clearCookies() {
        return CookieUtil.remove(COOKIE_KEY_CURRENT_USER);
    }
}